package com.learn.algorithm_1021;

/**
 * 1021. 删除最外层的括号
 * https://leetcode-cn.com/problems/remove-outermost-parentheses/
 *
 * @author gatts, 2020/8/23 11:29
 */
public class Solution {

    /**
     * 输入字符串为 "(()())(())(()(()))"，原语化分解得到 "(()())" + "(())" + "(()(()))"
     * 删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
     *
     * @param S
     */
    public String removeOuterParentheses(String S) {
        int level = 0;
        StringBuilder builder = new StringBuilder();
        for (char c : S.toCharArray()) {
            if (')' == c)
                level --;
            //- 首位的"("要干掉，所以第一次循环不会执行这一步
            //- level > 0时，表示已经找到了最外的左括号，那么就把中间的部分都保留
            if (level > 0)
                builder.append(c);
            if ('(' == c)
                level ++;
        }
        return builder.toString();
    }

    //- ( ()() ) (()) ( () (()) )
    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = solution.removeOuterParentheses("(()())(())(()(()))");
        System.out.println(s);
        System.out.println(solution.removeOuterParentheses(s));
    }

}
